package com.leyou.search.mq;

import com.leyou.search.service.SearchService;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

import static com.leyou.common.constants.MQConstants.*;

// 监听mq
@Component
public class ItemListener {
    @Resource
    private SearchService searchService;

    //商品上架,新增商品到索引库
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = QueueConstants.SEARCH_ITEM_UP, declare = "true")
            , exchange = @Exchange(name = ExchangeConstants.ITEM_EXCHANGE_NAME, type = ExchangeTypes.TOPIC)
            , key = RoutingKeyConstants.ITEM_UP_KEY
    ))
    public void listenItemUp(Long spuId) {
        if (spuId != null) {
            searchService.saveGoodsById(spuId);
        }
    }

    //商品下架，删除索引库里对应商品
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = QueueConstants.SEARCH_ITEM_DOWN, durable = "true"),
            exchange = @Exchange(name = ExchangeConstants.ITEM_EXCHANGE_NAME, type = ExchangeTypes.TOPIC),
            key = RoutingKeyConstants.ITEM_DOWN_KEY
    ))
    public void listenItemDown(Long spuId) {
        if (spuId != null) {
            searchService.deleteGoodsById(spuId);
        }
    }
}
